<?php
/**
* query templates objects
*
* may use Datapath if available
*
* This file is part of Webappkit, a packages system for PHP web apps
* @link http://webappkit.net
* @package webappkit
* @subpackage db
* @author J.Ducastel <jeremie@ducastel.name>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/
class DbQueryTpl extends uTpl {


    function __construct($str,$id=null) {
        parent::__construct($str);
        $this->id=$id;
    }
    function DbQueryTpl($str,$id=null) {
        $this->__construct($str,$id);
    }

    /**
     * sets null bollean value (for conditional blocks)
     * @param bool $bool
     * @return bool
     */
    function setNullBool($bool) {
        if (!is_bool($bool))
            return false;
        $this->null_bool=$bool;
        return true;
    }

    /**
     * render template with params to usable SQL
     * @param array $data request parameters
     * @param string escape strings function, default to mysql_escape_string
     * @return string
     */
    function render($data=array(),$escape_func='mysql_escape_string') {
        // getting vars if object
        if (is_object($data))
            $data=get_object_vars($data);
        // escaping strings with required function
        if ($escape_func and is_array($data)) {
            foreach ($data as $key => $value)
                if (is_string($value))
                    $data[$key]=$escape_func($value);
        }
        return parent::render($data);
    }

    /**
     * evaluates parameter to boolean, used for conditional blocks
     * @param mixed $var
     * @return bool
     */
    function _bool($var) {
        switch (true) {
            case $var: // var evaluates to true
                return true;
            case is_numeric($var): // always true
                return true;
            case is_string($var): // always true
                return true;
            case is_null($var):
                return $this->null_bool;
            default:
                return false;
        }
    }

    /**
     * add quotes around strings
     */
    function _strValue($var) {
        return '\''.$var.'\'';
    }

    function _nullValue() {
        return 'NULL';
    }
    
    function _boolValue($value) {
        return $value?'1':'0';
    }

    function _objectValue($var) {
        return serialize($var);
    }

    /**
     * @var string unique id (for storage)
     */
    var $id;

    /**
     * @var bool what null evaluates to
     */
    var $null_bool=true;
}
